package com.promise.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.promise.controller.result.AutomateResult;
import com.promise.pojo.Automate;
import com.promise.service.AutoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/automates")
public class AutomateController {
    @Autowired
    private AutoServiceImpl autoService;

    /**
     * 分页查询记录
     *
     * @param currentPage 当前页码
     * @param pageSize    页面数据条数
     * @param searchData  搜索条件
     * @return AutomateResult 分页查询结果
     */
    @PostMapping("/{currentPage}/{pageSize}")
    @ResponseBody
    public AutomateResult getAutomateByPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize,
                                            @RequestBody Automate searchData) {
        // 查询条件
        LambdaQueryWrapper<Automate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(searchData.getAutomateDate()),
                        Automate::getAutomateDate, searchData.getAutomateDate())
                .eq(!StringUtils.isEmpty(searchData.getReceiverId()),
                        Automate::getReceiverId, searchData.getReceiverId());

        IPage<Automate> iPage = new Page<>(currentPage, pageSize);
        IPage<Automate> page = autoService.page(iPage, queryWrapper);
        Integer code = page.getRecords() != null ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = page.getRecords() != null ? "查询成功" : "查询失败";
        Map<String, Object> data = new HashMap<>();
        data.put("pages", page.getPages());
        data.put("currentPage", page.getCurrent());
        data.put("pageSize", page.getSize());
        data.put("automates", page.getRecords());
        data.put("total", page.getTotal());
        return new AutomateResult(code, data, msg);
    }

    /**
     * 根据automateId删除
     *
     * @param automateId id
     * @return AutomateResult
     */
    @DeleteMapping("delete/{automateId}")
    @ResponseBody
    public AutomateResult delete(@PathVariable Integer automateId) {
        boolean flag = autoService.removeById(automateId);
        Integer code = flag ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = flag ? "删除成功" : "删除失败";
        return new AutomateResult(code, flag, msg);
    }


    /**
     * 根据ID更新自动化记录
     *
     * @param automateId 要更新的记录的ID
     * @param updateData 包含更新数据的对象
     * @return AutomateResult 更新结果
     */
    @PutMapping("update/{automateId}")
    @ResponseBody
    public AutomateResult updateAutomate(@PathVariable Integer automateId, @RequestBody Automate updateData) {
        // 检查传入的ID是否有效
        if (automateId == null || automateId <= 0) {
            return new AutomateResult(Code.ERROR_CODE, null, "无效的ID");
        }

        // 将传入的ID设置到更新数据对象中
        updateData.setAutomateId(automateId);

        // 调用服务层的更新方法
        boolean isUpdated = autoService.updateById(updateData);

        // 根据更新结果设置返回状态码和消息
        Integer code = isUpdated ? Code.SUCCESS_CODE : Code.ERROR_CODE;
        String msg = isUpdated ? "更新成功" : "更新失败";

        // 返回更新结果
        return new AutomateResult(code, isUpdated, msg);
    }


    /**
     * 新增自动化记录
     *
     * @param automate 要新增的自动化记录对象
     * @return AutomateResult 新增结果
     */
    @PostMapping("/add")
    @ResponseBody
    public AutomateResult addAutomate(@RequestBody Automate automate) {
        try {
            boolean saveResult = autoService.save(automate);
            Integer code = saveResult ? Code.SUCCESS_CODE : Code.ERROR_CODE;
            String msg = saveResult ? "新增成功" : "新增失败";
            return new AutomateResult(code, saveResult, msg);
        } catch (Exception e) {
            // 记录异常信息，实际开发中应该使用日志框架记录
            e.printStackTrace();
            return new AutomateResult(Code.ERROR_CODE, false, "系统异常，新增失败");
        }
    }
}
